package com.hgy.plugin.soap.helper;

import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.message.Message;

import com.hgy.plugin.soap.SoapConfig;

/**
 * SOAP 助手类
 * 
 * @author alone
 *
 */
public class SoapHelper {

	//日志输出
	private static final List<Interceptor<? extends Message>> inInterceptorList = new ArrayList<Interceptor<? extends Message>>();
	private static final List<Interceptor<? extends Message>> outInterceptorList = new ArrayList<Interceptor<? extends Message>>();
	
	static{
		if (SoapConfig.isLog()) {
			LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
			inInterceptorList.add(loggingInInterceptor);
			LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
			outInterceptorList.add(loggingOutInterceptor);
		}
	}
	
	/**
	 * 发布 SOAP 服务
	 * 
	 * @param wsdl
	 * @param interfaceClass
	 * @param implementInstance
	 */
	public static void publishService(String wsdl, Class<?> interfaceClass, Object implementInstance){
		
		ServerFactoryBean factory = new ServerFactoryBean();
        factory.setAddress(wsdl);
        factory.setServiceClass(interfaceClass);
        factory.setServiceBean(implementInstance);
        factory.setInInterceptors(inInterceptorList);
        factory.setOutInterceptors(outInterceptorList);
        factory.create();
		
	}
	
	
	/**
	 * 创建SOAP 客户端
	 * @param wsdl
	 * @param interfaceClass
	 * @return
	 */
	public static <T> T createClient(String wsdl, Class<? extends T> interfaceClass) {
		
        ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
        factory.setAddress(wsdl);
        factory.setServiceClass(interfaceClass);
        factory.setInInterceptors(inInterceptorList);
        factory.setOutInterceptors(outInterceptorList);
        return factory.create(interfaceClass);
    }
}
